package com.frt.sygang.filter;/**
 * Created by 冯瑞涛 on 2022/9/17 14:55
 */

import com.alibaba.fastjson.JSONObject;
import com.frt.sygang.common.BaseContext;
import com.frt.sygang.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.Local;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 冯瑞涛
 * @version 1.0
 * @date 2022/9/17 14:55
 */
@Slf4j
@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取本次请求的url
        String requestURI = request.getRequestURI();
        String[] lightUrls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //2.判断是否需要过滤
        boolean check = check(requestURI, lightUrls);
        //3.如果不需要过滤则直接放行
        if (check) {
            log.info(requestURI + "不需要处理");
            filterChain.doFilter(request, response);
            return;
        }
        //4.若已经登录这直接放行
        Long id = (Long) request.getSession().getAttribute("employee");
        if (id!= null) {
            BaseContext.setCurrentId(id);
            filterChain.doFilter(request, response);
            return;
        }

        //手机登录验证放行
        Long user = (Long) request.getSession().getAttribute("user");
        if(user!=null){
            BaseContext.setCurrentId(user);
            filterChain.doFilter(request, response);
            return;
        }
        //5.如果未登录则跳转到登录页面
        response.getWriter().write(JSONObject.toJSONString(R.error("NOTLOGIN")));
    }

    private boolean check(String requestURI, String[] lightUrls) {
        for (String lightUrl : lightUrls) {
            boolean match = PATH_MATCHER.match(lightUrl, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
